package com.bjsxt.shop.back.springmvc.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bjsxt.common.util.ConstatFinalUtil;
import com.bjsxt.common.util.PageInfoUtil;
import com.bjsxt.shop.common.controller.BaseController;
import com.bjsxt.shop.goods.pojo.AGoods;
import com.bjsxt.shop.goods.pojo.AGoodsBrand;
import com.bjsxt.shop.goods.pojo.AGoodsCate;
import com.bjsxt.shop.goods.pojo.AGoodsCateEnum;
import com.bjsxt.shop.goods.service.IGoodsService;
import com.bjsxt.shop.users.pojo.AAdmins;

@Controller
@RequestMapping("/back/goods/")
public class GoodsBackController extends BaseController
{
	@Resource
	private IGoodsService goodsService;
	
	@RequestMapping("/brandList")
	public String brandList()
	{
		ConstatFinalUtil.SYS_LOGGER.info("---brandList--");
		return "/back/goods/brandList" ; 
	}
	
	@RequestMapping(value="/brandListJSON",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String brandListJSON(String page,String rows)
	{
	    ConstatFinalUtil.SYS_LOGGER.info("-----brandListJSON-----");
	    PageInfoUtil pageInfoUtil=this.proccedPageInfo(page, rows);
	    Map<String, Object> condMap=new HashMap<>();
	    /*查询列表*/
	    Map<String, Object> resultMap=this.goodsService.findCondListGoodsBrandService(pageInfoUtil, condMap);
	    /*数据*/
	    List<AGoodsBrand> brandList=(List<AGoodsBrand>) resultMap.get("list");
	    int totalRecord=Integer.valueOf(resultMap.get("totalRecord")+"");
	    /*拼装JSON*/
	    JSONObject resultJSON=new JSONObject();
	    resultJSON.put("total", totalRecord);
	    
	    JSONArray dataArr=new JSONArray();
	    int count=1;
	    for (Iterator iterator = brandList.iterator(); iterator.hasNext();)
		{
	    	AGoodsBrand brand = (AGoodsBrand) iterator.next();
	    	JSONObject brandJSON=brand.toJSON();
	    	brandJSON.put("count", count);
			/*数据*/
	    	dataArr.add(brandJSON);
	    	count++;
		}
	    resultJSON.put("rows", dataArr);
	    return resultJSON.toJSONString(); 
	}
	
    /*品牌添加
     * 
     * */
	@RequestMapping("/brandInsert")
	public String brandInsert()
	{
		ConstatFinalUtil.SYS_LOGGER.info("---brandInsert--");
		return "/back/goods/brandInsert" ; 
	}
	
	@RequestMapping(value="/brandInsertSubmit",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String brandInsertSubmit(String pubtimeStr,AGoodsBrand goodsBrand,HttpSession session,MultipartFile file)
	{
		ConstatFinalUtil.SYS_LOGGER.info("-----brandInsertSubmit----");
		JSONObject resultJSON=new JSONObject();
		/*文件上传*/
		if(file!=null&&!"".equalsIgnoreCase(file.getOriginalFilename()))
		{
			String originalFilename=file.getOriginalFilename();
			String fileName="";
			try
			{
				String ralePath=ConstatFinalUtil.CONFIG_JSON.getString("relaPath");
				ralePath+="/brand/"+this.dateFormatUtil.dateStr(new Date());
				fileName=UUID.randomUUID().toString()+originalFilename.substring(originalFilename.lastIndexOf("."), originalFilename.length());
				boolean flag=this.ftpUtil.uploadFile(fileName, ralePath, file.getInputStream());
				if(flag)
				{
					goodsBrand.setLogoPath(ralePath+fileName);
				}
			} catch (IOException e)
			{
				ConstatFinalUtil.SYS_LOGGER.error("上传文件失败了,文件名:{}",fileName,e);
			}
		}
		goodsBrand.setPubTime(this.dateFormatUtil.strDateTime(pubtimeStr));
		
		AAdmins adminsSess = (AAdmins) session.getAttribute("admins");
		goodsBrand.setAdminsId(adminsSess.getId());
		goodsBrand.setCreateTime(new Date());
		goodsBrand.setUpdateTime(new Date());
		/**
		 * 保存数据
		 */
		resultJSON = this.goodsService.saveOneGoodsBrandService(goodsBrand);
		return resultJSON.toJSONString() ; 
	}
	
	/**
	 * 商品模块开始管理
	 */
	@RequestMapping("/goodsList")
	public String goodsList()
	{
		ConstatFinalUtil.SYS_LOGGER.info("==goodsList===");
		return "/back/goods/goodsList" ; 
	}
	@RequestMapping(value="/goodsListJSON",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String goodsListJSON(HttpServletRequest request,String page,String rows,String keyword,String status,String st,String ed)
	{
		/*try
		{
			keyword=new String(keyword.getBytes("ISO8859-1"), "UTF-8");
		} catch (Exception e)
		{
		}*/
		PageInfoUtil pageInfoUtil=this.proccedPageInfo(page,rows);
		if(status==null)
		{
		   status="";	
		}
		if(st==null)
		{
		   st="";	
		}
		if(ed==null)
		{
		   ed="";	
		}
		Date stDate=null;
		Date edDate=null;
		if(!"".equalsIgnoreCase(st)&&!"".equalsIgnoreCase(ed))
		{
			stDate=this.dateFormatUtil.strDateTime(st);
			edDate=this.dateFormatUtil.strDateTime(ed);
		}
		Map<String, Object> condMap=new HashMap();
		condMap.put("keyword", keyword);
		if(!"".equalsIgnoreCase(status))
		{
			condMap.put("status", status);
		}
		condMap.put("stDate", stDate);
		condMap.put("edDate", edDate);
		
		Map<String, Object> resultMap=this.goodsService.findCondListGoodsService(pageInfoUtil, condMap);
		List<AGoods> goodsList=(List<AGoods>) resultMap.get("list");
		int totalRecord=Integer.valueOf(resultMap.get("totalRecord")+"");
		JSONObject resultJSON=new JSONObject();
		resultJSON.put("total", totalRecord);
		JSONArray dataArr=new JSONArray();
		for (Iterator iterator = goodsList.iterator(); iterator.hasNext();)
		{
			AGoods goodsTemp = (AGoods) iterator.next();
			JSONObject goodsJSON=goodsTemp.toJSON();
			dataArr.add(goodsJSON);
		}
		resultJSON.put("rows", dataArr);
		return resultJSON.toJSONString();
	}
	
	/*打开商品添加页面*/
	@RequestMapping("/goodsInsert")
	private String goodsInsert(Model model)
	{
		Map<String, Object> condMap=new HashMap<>();
		condMap.clear();
		condMap.put("status", AGoodsCateEnum.STATUS_ENABLE.getStatus());
		Map<String, Object> resultMap=this.goodsService.findCondListGoodsBrandService(null, condMap);
		List<AGoodsBrand> brandList=(List<AGoodsBrand>) resultMap.get("list");
		model.addAttribute("brandList", brandList);
		List<AGoodsCate> goodsCateTreeList=this.goodsService.findTreeListCateService();
		model.addAttribute("goodsCateTreeList", goodsCateTreeList);
		
	 	return "/back/goods/goodsInsert";
	}
	/*商品提交页面*/
	@RequestMapping(value ="/goodsInsertSubmit",produces="text/html;charset=UTF-8")
	@ResponseBody
	private String goodsInsertSubmit(AGoods goods,String pubtimeStr,HttpSession session,HttpServletRequest request)
	{
		ConstatFinalUtil.SYS_LOGGER.info("-------goodsInsertSubmit-------");
		JSONObject resultJSON=new JSONObject();
		/*拼装JSON*/
	    Map<String, Object> condMap=new HashMap<>();
	    condMap.put("id", goods.getCateId());
	    AGoodsCate goodsCate=this.goodsService.findOneGoodsCateService(condMap);
	    System.out.println(goodsCate);
	    JSONArray specArr=goodsCate.getSpecArr();
	    System.out.println(specArr+" ----------------------------");
		/*
		 * request.getParameter("spec_功能_制冷类型")
		 * [
				{
					"name": "功能",
					"keys": [
					{
						"name":"制冷类型",
						"values":"冷暖"
					}
				}
			]
		 * */
	    for (Iterator iterator = specArr.iterator(); iterator.hasNext();)
		{
			JSONObject jsonTemp1 = (JSONObject) iterator.next();
			JSONArray keysArr=(JSONArray) jsonTemp1.get("keys");
			for (Iterator iterator2 = keysArr.iterator(); iterator2.hasNext();)
			{
				JSONObject jsonKeyTemp2 = (JSONObject) iterator2.next();
				/* value从哪来? */
				String keyParam="spec_"+jsonTemp1.get("name")+"_"+jsonKeyTemp2.get("name");
				/* key:是不确定的 */
				String value=request.getParameter(keyParam);
				jsonKeyTemp2.put("values", value);	
			}
			
		}
	    /* 将分类中的规格values由原来的数组变成了值 */
	    goods.setSpec(specArr.toJSONString());
	    
	    AAdmins adminsSess = (AAdmins) session.getAttribute("admins");
		/* 自己来转换时间,就不用转换器了 */
		goods.setPubTime(this.dateFormatUtil.strDateTime(pubtimeStr));
		
		/* 把页面上木有赋值的属性,赋值一下 */
		/* 从Session中获取 */
		goods.setAdminsId(adminsSess.getId());
		goods.setCreateTime(new Date());
		goods.setUpdateTime(new Date());
		
		/* 上传文件 */
		resultJSON = this.goodsService.saveOneGoodsService(goods);
		return resultJSON.toJSONString(); 
	}
}
